/**
 * 
 */
package com.zjtobacco.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.zjtobacco.domain.User;

/**
 * @author 
 * 
 */
@Controller
@RequestMapping("/user")
public class UserController {
	@RequestMapping("loginCheck")
	public ModelAndView loginCheck(User user) {
		Subject currentUser = SecurityUtils.getSubject();
		String result="login";
		if (!currentUser.isAuthenticated()) {
			result = login(currentUser,user.getUsername(),user.getPassword());
		}else{//重复登录
			User currentuser = (User) currentUser.getPrincipal();
			if(!currentuser.getUsername().equalsIgnoreCase(user.getUsername())){//如果登录名不同
				currentUser.logout();
				result = login(currentUser,user.getUsername(),user.getPassword());
			}else{
				result="success";
			}
		}
		ModelAndView modelAndView=null;
		if(result.equals("success")){
			 modelAndView = new ModelAndView("success");
		}
		else{
		 modelAndView = new ModelAndView("login");
		modelAndView.addObject("result", result);
		}
		return modelAndView;
		
		
	}
	@RequestMapping("login")
	public ModelAndView login(User user) {
	
		return new ModelAndView("login");
		
	}
	private String login(Subject currentUser,String username,String password){
		String result = "login";
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		token.setRememberMe(false);
		try {
			currentUser.login(token);
			result = "success";
		} catch (UnknownAccountException uae) {
			result = "failure";
		} catch (IncorrectCredentialsException ice) {
			result = "failure";
		} catch (LockedAccountException lae) {
			result = "failure";
		} catch (AuthenticationException ae) {
			result = "failure";
		}
		return result;
	}

	@RequestMapping("success")
	public ModelAndView main() {
		ModelAndView modelAndView = new ModelAndView("success");
		return modelAndView;
	}


	
}
